package org.xsk.network.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * description: 基于UDP协议的服务器
 * <p>
 * date: 2021/6/10 13:38
 * author: x-one
 */
public class LoginServer {
    public static void main(String[] args) {
        DatagramSocket socket=null;

        try {
            //接收客户端发过来的请求
            //1、建立一个空包用来收
            byte[] b =new byte[1024];
            DatagramPacket dp = new DatagramPacket(b, b.length);
            //2、创建DatagramSocket，（快递点）
            socket =new DatagramSocket(8000);
            //3、收数据
            socket.receive(dp);
            //读取数据
            String info = new String(dp.getData(),0,dp.getData().length);
            System.out.println("客户端说："+info);


            //给客户端一个响应
            String reply = "我是服务器，你好，客户端！";
            DatagramPacket dp1=new DatagramPacket(reply.getBytes(), reply.getBytes().length, InetAddress.getByName("localhost"), 8000);
            //不用再创建socket
            socket.send(dp1);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null!=socket) {
                socket.close();
            }
        }
    }
}
